/* Created By TheBrodieMan */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using CommonBehaviors.Actions;
using System.Windows.Forms;
using System.Windows.Media;
using Styx;
using Styx.Common;
using Styx.CommonBot;
using Styx.CommonBot.Profiles;
using Styx.Pathing;
using Styx.TreeSharp;
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;

using Action = Styx.TreeSharp.Action;

namespace Honorbuddy.Quest_Behaviors.SpecificQuests.CircleTheWagons
{
	[CustomBehaviorFileName(@"CircleTheWagons")]
	public class CircleTheWagons : CustomForcedBehavior
	{
		public CircleTheWagons(Dictionary<string, string> args)
			: base(args)
		{
		try
			{
				QuestId = GetAttributeAsNullable<int>("QuestId", false, ConstrainAs.QuestId(this), null) ?? 0;
			}
			catch
			{
				Logging.Write("Problem parsing a QuestId in behavior: Pirate Accuracy Increasing");
			}
		}

		public int QuestId { get; set; }
		public static LocalPlayer Me { get { return StyxWoW.Me; } }
		public WoWUnit Boats = null;
		
		private bool _isDone;
		public override bool IsDone
		{
			get
			{
				return _isDone;
			}
		}
		
		public Composite DoneYet
		{
			get
			{
				return
					new Decorator(ret => IsQuestComplete(), new Action(delegate
					{
						TreeRoot.StatusText = "Finished!";
						Lua.DoString("VehicleExit()");
						_isDone = true;
						return RunStatus.Success;
					}));
			}
		}
		
		public bool IsQuestComplete()
		{
			var quest = StyxWoW.Me.QuestLog.GetQuestById((uint)QuestId);
			return quest == null || quest.IsCompleted;
		}
		
		private Composite _root;
		protected override Composite CreateBehavior()
		{
			return _root ?? (_root = new Decorator(ret => !_isDone,
				new PrioritySelector(
					new Decorator(ret => !Me.HasAura(75912),
						new Action(ret => { _isDone = true; })),
					DoneYet,
					new Sequence(
						new Action(ret => 
						{
							Boats = ObjectManager.GetObjectsOfType<WoWUnit>(true)
									.Where(u => u.Entry == 40707)
									.OrderBy(u => u.Distance)
									.FirstOrDefault();
							
							RunStatus runStatus = Boats == null || !Boats.IsValid
								? RunStatus.Failure
								: RunStatus.Success;
								
							return runStatus;
						}),
						new Action(ret => Boats.Interact()),
						new Action(ret => Lua.DoString("CastPetAction(1)")),
						new Action(ret => StyxWoW.Sleep(1500)),
						new Action(ret => SpellManager.ClickRemoteLocation(Boats.Location)),
						new Action(ret => StyxWoW.Sleep(1500))
			))));
		}
	}
}

